<script setup lang="ts">
import useAction from "./action";
import { LOOP_MODE, loopColumns } from "@/global/const";
import CurrentList from './current-list.vue'

const props = defineProps({
  autoPlay: {
    type: Boolean,
    default: false
  }
})

const {
  isPlaying,
  currentTime,
  duration,
  formatTime,
  initAudio,
  changeMusic,
  sliderChange,
  togglePlay,
  musicEnded,
} = useAction()

const musicStore = useMusicStore();

const currentMusic = computed(() => musicStore.currentMusic);

const currentmusicList = computed(() => musicStore.currentMusicList);

/** 获取当前播放的音乐 */
function getCurrentMusic(event: AudiopalyRecord = null) {
  if(event && event.path) return true;

  if(currentMusic.value.path) return true;

  uni.showToast({
    title: '请选择音乐播放',
    icon: 'none',
    duration: 2000
  });

  return false;
}

/** 切换音乐播放 */
function changeMusicPlay(event: AudiopalyRecord) {
  if (!getCurrentMusic()) return
  musicStore.setCurrentMusic(event);
  changeMusic(currentMusic.value.path);
  if (!isPlaying.value) togglePlay();
}

/** 上一曲 */
function previousMusic() {
  if (!getCurrentMusic()) return
  const musicIndex = currentmusicList.value.findIndex(item => item.path === currentMusic.value.path);
  if (musicStore.loopType == LOOP_MODE.RANDOM) {
    changeMusicPlay(currentmusicList.value[Math.floor(Math.random() * currentmusicList.value.length)]);
  } else if (musicIndex === 0) {
    changeMusicPlay(currentmusicList.value[currentmusicList.value.length - 1]);
  } else {
    changeMusicPlay(currentmusicList.value[musicIndex - 1]);
  }
}

/** 播放暂停 */
function toggleMusicPlay() {
  if (!getCurrentMusic()) return
  if (currentMusic.value.path) {
    togglePlay();
  } else {
    changeMusicPlay(currentmusicList.value[0])
  }
}

/** 播放下一曲 */
function nextMusic() {
  if (!getCurrentMusic()) return
  const musicIndex = currentmusicList.value.findIndex(item => item.path === currentMusic.value.path);
  if (musicStore.loopType == LOOP_MODE.RANDOM) {
    changeMusicPlay(currentmusicList.value[Math.floor(Math.random() * currentmusicList.value.length)]);
  } else if (musicIndex === currentmusicList.value.length - 1) {
    changeMusicPlay(currentmusicList.value[0]);
  } else {
    changeMusicPlay(currentmusicList.value[musicIndex + 1]);
  }
}

/** 播放结束 播放下一首 */
musicEnded(() => {
  if (musicStore.loopType == LOOP_MODE.SINGLE_CYCLE) {
    toggleMusicPlay()
  } else if (musicStore.loopType == LOOP_MODE.SEQUENCE) {
    const musicIndex = currentmusicList.value.findIndex(item => item.path === currentMusic.value.path);
    if (musicIndex < currentmusicList.value.length - 1) {
      nextMusic()
    }
  } else {
    nextMusic()
  }
})

/** 打开播放界面 */
function playMusic(path: string = '') {
  if (!path) {
    uni.showToast({
      title: '请选择音乐播放',
      icon: 'none',
      duration: 2000
    });
    return ;
  }

  uni.navigateTo({
    url: `/pages/audiopaly/index?path=${path}`
  });
}
/** 当前播放列表弹窗 */
const menuVisible = ref(false);

/** 打开音乐选择弹窗 */
function openMenu() {
  menuVisible.value = true;
}


// 新增媒体键事件处理相关变量和函数
let lastVolumeUpPress = 0;
let lastVolumeDownPress = 0;

/** 媒体键事件处理 */
const handleMediaKeyEvent = () => {
  plus.key.addEventListener("volumeupbutton", onVolumeKey, false);
  plus.key.addEventListener("volumedownbutton", onVolumeKey, false);
  plus.key.addEventListener("mediabutton", onMediaKey, false); // 将"media"改为"mediabutton"
};

/** 媒体键事件处理 */
const onVolumeKey = (type: PlusKeyKeyEvent) => {
  const now = Date.now();
  if (type.keyType == 'volumeup') {
    if (now - lastVolumeUpPress < 500) {
      increaseVolume();
    }
    lastVolumeUpPress = now;
  } else {
    if (now - lastVolumeDownPress < 500) {
      decreaseVolume();
    }
    lastVolumeDownPress = now;
  }
};

/** 媒体键事件处理 */
const onMediaKey = (e: any) => {
  if (e.keyCode === plus.key.KEY_MEDIA_PLAY) {
    togglePlay();
  }

};

/** 音量增加 媒体键事件处理 */
const increaseVolume = () => {
  // 实现音量增加逻辑（需根据实际音频API调整）
  previousMusic();
};

/** 音量减少 媒体键事件处理 */
const decreaseVolume = () => {
  // 实现音量减少逻辑（需根据实际音频API调整）
  nextMusic();
};

/** 设置循环类型 */
function setLoopType() {
  let loopIndex = loopColumns.findIndex(item => item.value === musicStore.loopType);
  if (loopIndex + 1 >= loopColumns.length) {
    musicStore.setLoopType(loopColumns[0].value);
  } else {
    musicStore.setLoopType(loopColumns[loopIndex + 1].value);
  }

  let loopActive = loopColumns[loopIndex + 1] || loopColumns[0];
  uni.showToast({
    title: loopActive.label,
    icon: 'none',
    duration: 2000
  });
}

onMounted(() => {
  initAudio();
  if (currentMusic.value.path) {
    if (props.autoPlay) {
      changeMusicPlay(currentMusic.value);
    } else {
      changeMusic(currentMusic.value.path);
    }
  }
  handleMediaKeyEvent()
});

// 移除事件监听
onUnload(() => {
  plus.key.removeEventListener("volumeupbutton", onVolumeKey);
  plus.key.removeEventListener("volumedownbutton", onVolumeKey);
  plus.key.removeEventListener("mediabutton", onMediaKey); // 对应修改为"mediabutton"
});
</script>

<template>
  <view class="play-music-box">
    <view class="play-box">
      <view class="music-info">
        <view class="play-img" @click="playMusic(currentMusic.path)">
          <image src="/static/image/audiopaly/music-a.png" mode="aspectFit"></image>
        </view>
        <view class="play-info" @click="playMusic(currentMusic.path)">
          <view class="play-name">
            <text>{{ currentMusic.musicName }}</text>
          </view>
          <view class="play-author">
            <text>{{ currentMusic.author }}</text>
          </view>
        </view>
      </view>
      <!--   循环类型   -->
      <view class="loop-menu">
        <view class="loop-btn" @click="setLoopType">
          <image src="/static/image/play-music-box/sequence.svg" v-if="musicStore.loopType == LOOP_MODE.SEQUENCE" />
          <image src="/static/image/play-music-box/random.svg" v-if="musicStore.loopType == LOOP_MODE.RANDOM" />
          <image src="/static/image/play-music-box/single_cycle.svg"
                 v-if="musicStore.loopType == LOOP_MODE.SINGLE_CYCLE" />
          <image src="/static/image/play-music-box/loop.svg" v-if="musicStore.loopType == LOOP_MODE.LOOP" />
        </view>
        <view class="loop-box">

        </view>
      </view>
      <view class="play-control">
        <view class="play-btn" @click="previousMusic()">
          <image src="/static/image/audiopaly/previous.svg" />
        </view>
        <view
            class="play-btn"
            :class="{ playing: isPlaying }"
            @click="toggleMusicPlay"
        >
          <image :src="`/static/image/audiopaly/${ isPlaying ? 'pause': 'play' }.svg`" />
        </view>
        <view class="play-btn" @click="nextMusic()">
          <image src="/static/image/audiopaly/next.svg" />
        </view>

      </view>
      <view class="paly-menu" @click="openMenu">
        <image src="/static/image/play-music-box/menu.svg" />
      </view>
    </view>
    <!-- 进度条 -->
    <view class="progress-bar">
      <view class="time">{{ formatTime(currentTime) }}</view>
      <slider
          :value="currentTime"
          :max="duration"
          :block-size="autoPlay? 15: 0"
          activeColor="#007AFF"
          @changing="sliderChange"
          @change="sliderChange"
      />
      <view class="time">{{ formatTime(duration) }}</view>
    </view>
    <!-- 音乐选择弹窗 -->
    <current-list v-model="menuVisible" @change="changeMusicPlay" />
  </view>
</template>

<style scoped lang="scss">
.play-music-box {
  position: fixed;
  bottom: 0;
  width: 670rpx;
  height: 110rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  z-index: 998;

  // #ifdef WEB
  & {
    bottom: 100rpx;
  }
  // #endif


  .play-box {
    width: 100%;
    display: flex;
    align-items: center;
    height: 100rpx;

    .music-info {
      display: flex;
      margin-right: auto;
      align-items: center;

      .play-img {
        width: 80rpx;
        height: 80rpx;
        margin-right: 20rpx;
      }

      .play-info {

        width: 300rpx;

        .play-name {
          font-size: 17px;
          margin-bottom: 8rpx;
          height: 40rpx;
          width: 300rpx;
          overflow: hidden; //超出隐藏
          white-space: nowrap; //不换行，同一行展示
          text-overflow: ellipsis; //设置超出部分以省略号展示
        }

        .play-author {
          font-size: 14px;
          color: #999;
        }
      }
    }

    .play-control {
      display: flex;

      .play-btn {
        transition: all 0.3s;
        width: 40rpx;
        height: 40rpx;

        margin: 0 10rpx;
      }

    }

    .paly-menu {
      width: 40rpx;
      height: 40rpx;
      margin-left: 20rpx;
    }
  }

}

.play-music-mall{
  background-color: #fafaad;
  .progress-bar {
    display: flex;
    align-items: center;

    .time {
      font-size: 0rpx;
      color: #666;
      width: 0rpx;
    }

    slider {
      flex: 1;
      margin: 0;
    }

    :deep(uni-slider) {
      .uni-slider-wrapper {
        min-height: 6px;
      }

      .uni-slider-tap-area {
        background-color: #1c84c6;
        padding: 0;
      }
    }
  }
}

.play-music-more {
  background-color: transparent;
  position: static;
  width: 650rpx;
  height: 148rpx;

  .play-box {

    .music-info {
      display: none;
    }

    .loop-menu{
      width: 40rpx;
      height: 40rpx;
      margin-right: 20rpx;

      .loop-btn {
        width: 40rpx;
        height: 40rpx;
      }
    }

    .play-control {
      flex: 1;
      justify-content: center;
      .paly-menu{
        margin-left: 0;
      }
    }

    .paly-menu {
    }
  }

  .progress-bar {
    display: flex;
    align-items: center;

    .time {
      font-size: 24rpx;
      color: #fff;
      min-width: 60rpx;
      text-align: center;
    }

    slider {
      flex: 1;
      //margin: 0 20rpx;
    }
  }
}
</style>